package com.study.leetcode;


import java.util.HashMap;
import java.util.Map;

//https://leetcode-cn.com/problems/zigzag-conversion/
public class Solution_6 {
    public String convert(String s, int numRows) {
        //特判
        if (numRows >= s.length() || numRows == 1) return s;
        Map<Integer, String> zMap = new HashMap<>();
        int index = 0;
        boolean direct = true;
        for (int i = 0; i < s.length(); i++) {
            if (zMap.get(index) == null) {
                zMap.put(index, String.valueOf(s.charAt(i)));
            } else {
                zMap.put(index, zMap.get(index) + s.charAt(i));
            }
            //这里就是Z字形转折的控制
            if (direct) {
                index++;
                if (index > numRows - 1) {
                    direct = false;
                    index = numRows - 2;
                }
            } else {
                index--;
                if (index < 0) {
                    direct = true;
                    index = 1;
                }
            }
        }
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < zMap.size(); i++) {
            result.append(zMap.get(i));
        }
        return result.toString();
    }
}
